//
//  WmcAlbumSelectProjectsCell.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/23.
//

import UIKit
import YPBedrock

class WmcSystemAlbumSelectProjectsCell: WmcBaseTableCell {
    lazy var checkMarkImageView: UIImageView = {
        let imageView = UIImageView(image: "check_mark".wmc_image)
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()

    override func makeUI() {
        addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.left.equalTo(Wmc_standardEdge.left)
            make.right.equalTo(Wmc_standardEdge.right)
            make.height.equalTo(0.5)
            make.bottom.equalToSuperview()
        }

        wmc_imageView.contentMode = .scaleToFill
        wmc_imageView.clipsToBounds = true
        wmc_imageView.layer.cornerRadius = 4
        addSubview(wmc_imageView)
        wmc_imageView.snp.makeConstraints { make in
            make.left.equalTo(lineView)
            make.top.equalTo(Wmc_standardEdge.top)
            make.bottom.equalTo(lineView.snp.top).offset(-Wmc_standardEdge.bottom)
            make.width.equalTo(wmc_imageView.snp.height)
        }

        addSubview(checkMarkImageView)
        checkMarkImageView.snp.makeConstraints { make in
            make.centerY.equalTo(wmc_imageView)
            make.right.equalTo(-Wmc_standardEdge.right)
            make.size.equalTo(22)
        }

        titleLabel.font = 18.wmc_font
        titleLabel.textColor = .wmc_grayH2_323233
        titleLabel.numberOfLines = 0
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.bottom.equalTo(wmc_imageView)
            make.left.equalTo(wmc_imageView.snp.right).offset(Wmc_standardEdge.left)
            make.right.lessThanOrEqualTo(checkMarkImageView.snp.left).offset(-8)
        }
    }

    func configModel(_ model: WmcAlbumManager.AlbumModel) {
        // 优化列表滑动流畅性
        let cacheKey = model.description
        // 尝试读取
        let cacheImage: UIImage? = WmcCache.MemoryCacheRead(table: .imageTable, key: cacheKey)
        if let cacheImage {
            wmc_imageView.image = cacheImage
        } else { // 加载并缓存
            if let lastAsset = model.result.lastObject {
                // 异步加载
                WmcAlbumManager.asyncLoadImage(asset: lastAsset) { [weak self] image in
                    guard let weakSelf = self else { return }
                    weakSelf.wmc_imageView.image = image
                    // 存入缓存
                    WmcCache.MemoryCacheWrite(table: .imageTable, key: cacheKey, value: image)
                }
            }
        }
        titleLabel.text = "\(model.name)[\(model.count)]"
        checkMarkImageView.isHidden = !model.isSelected
    }
}
